﻿using Dapr.Actors;
using Dapr.Actors.Client;
using Microsoft.AspNetCore.Mvc;
using MyActor.Interfaces;

namespace ActorFactory.Controllers
{
    
    [ApiController]
    [Route("[controller]/[Action]")]
    public class WeatherController : ControllerBase
    { 
        private readonly IActorProxyFactory _actorProxyFactory;
        private readonly ILogger<WeatherController> _logger;



        public WeatherController(ILogger<WeatherController> logger, IActorProxyFactory actorProxyFactory)
        {
            _logger = logger;
            _actorProxyFactory = actorProxyFactory;
        }

        
        [HttpGet(Name = "Get")]
        public async Task<ActionResult> Create(string id)
        {
            var _items = new List<OrderItem>() { new OrderItem() { Product = new Product { Id = id }, Quantity = 2 } };
            Order order = new Order() { Items = _items };
            try
            {
                string responseId = "";
                // 扣除该订单每个商品的库存        
                foreach (var orderItem in order.Items)
                {
                    //产品Id作为 Actor Id            
                    var actorId = new ActorId(orderItem.Product.Id);
                    //创建调用代理, 只需知道接口(IInventory)即可            
                    var actorProxy = _actorProxyFactory.CreateActorProxy<IInventory>(actorId, "InventoryActor");
                    responseId = await actorProxy.SubtractAsync(orderItem, actorId);
                }
                return Ok(responseId);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }
        [HttpPost(Name = "Create")]
        public async Task<ActionResult> CreateOrder(string id)
        {
            var _items = new List<OrderItem>() { new OrderItem() { Product = new Product { Id = id }, Quantity = 2 } };
            Order order = new Order() { Items = _items };
            try
            {
                string responseId = "";
                // 扣除该订单每个商品的库存        
                foreach (var orderItem in order.Items)
                {
                    //产品Id作为 Actor Id            
                    var actorId = new ActorId(orderItem.Product.Id);
                    //创建调用代理, 只需知道接口(IInventory)即可            
                    var proxy = ActorProxy.Create<IInventory>(actorId, "InventoryActor");
                    responseId = await proxy.SubtractAsync(orderItem, actorId);
                }
                return Ok(responseId);
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }

    }
}